<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------
namespace app\api\controller\v2;

use app\model\car\CarOrderTake;
use app\Request;
use app\services\car\AlipayServices;
use app\services\car\BaseLogServices;
use app\services\car\CarOrderTakeServices;
use think\exception\ValidateException;

class AlipayController
{
    protected $alipay_public_key;
    protected $appid;
    protected $sign_type;
    protected $charset;
    protected $domain;
    protected $request = null;
    protected $services = null;

    public function __construct(Request $request,AlipayServices $services)
    {
        $this->request = $request;
        $this->services = $services;
    }

    /**
     * 获取支付宝系统配置
     * @version 2024-04-22
     * @return mixed
     */
    public function getConfigData()
    {
        // 小程序名称
        $data['alipay_routine_name'] = sys_config('alipay_routine_name');
        // 小程序logo
        $data['alipay_routine_logo'] = sys_config('alipay_routine_logo');
        // 查询页温馨提示
        $data['free_deposit_tip'] = sys_config('free_deposit_tip');
        // 查询页背景图片
        $data['free_deposit_background'] = sys_config('free_deposit_background');
        // 首页背景图
        $data['ali_homepage_background'] = sys_config('ali_homepage_background');
        // 个人中心背景图
        $data['personal_page_background'] = sys_config('personal_page_background');
        // 登录页背景图
        $data['login_head_image'] = sys_config('login_head_image');
        return app('json')->success($data);
    }


    /**
     * 支付宝冻结资金
     * @version 2024-04-22
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function AlipayFundAuthOrderAppFreezeRequest()
    {
        $data = $this->request->postMore([
            ['free_id', ''],
            ['type', 'free']
        ]);
        if(empty($data['free_id'])){
            return app('json')->fail('缺少参数');
        }
        return app('json')->success($this->services->AlipayFundAuthOrderAppFreezeRequest($data));
    }

    /**
     * 支付宝冻结资金回调
     * @version 2024-04-22
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function AlipayFundAuthOrderAppFreezeNotify()
    {
        file_put_contents('alipay2.txt' , json_encode($_POST));
        $data = json_encode($_POST);
        $data = '{"gmt_create":"2024-06-25 13:41:07","charset":"UTF-8","amount":"0.03","rest_amount":"0.03","notify_time":"2024-06-25 13:44:02","operation_type":"FREEZE","sign":"f64xpF4obs4\/FL7eEIzd8HUEfqoP7VyaB+xJOZLGrSFZy2Oiifvh7GSj9XcDnTzmhFpiLCuTfwL\/PQmJ6xh+UZ4MXaQ7x7+FUtR6l5bjsKNpaiIV2ey7ZwNtMqhLJfV1bQGZjO0uTEKWJOwcWN2PlOklrUHbH7DxH9JpVEyz4w946EfMjVO9kHjtVtBaFqFS4rce\/2c7OBRjnnMmNp+LZmOnAu1O5Fq\/HbRfGwnpH68OzZXqv1o5Z1mDo3Vc8+ldLM5k7f3MkZvT0B9R0BVwxtpvuIM9ZDCsDNsUBR4fuSVBRVGtXOdZpfHZiqe8cACrm18h89lVzq\/yLYpP1Bhd2g==","out_order_no":"F171929395012499402","version":"1.0","auth_no":"2024062510002001590524405951","notify_id":"2024062501222134126023771483340887","notify_type":"fund_auth_freeze","total_pay_amount":"0.00","total_freeze_amount":"0.03","gmt_trans":"2024-06-25 13:41:26","auth_app_id":"2021003160683131","operation_id":"20240625121400695905","total_unfreeze_amount":"0.00","out_request_no":"F171929395012499402","payer_user_id":"2088812336242597","app_id":"2021003160683131","sign_type":"RSA2","status":"SUCCESS","payer_logon_id":"107***@qq.com"}';
        return app('json')->success($this->services->AlipayFundAuthOrderAppFreezeNotify($data));
    }

    /**
     * 支付宝预授权转支付回调
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function AlipayTradePayRequestNotify()
    {
        $data = $_POST;
        return app('json')->success($this->services->AlipayTradePayRequestNotify($data));
    }

    /**
     * 预授权解冻回调
     * @version 2024-04-22
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function AlipayFundAuthOrderUnfreezeNotify()
    {
        $data = json_encode($_POST);
        return app('json')->success($this->services->AlipayFundAuthOrderUnfreezeNotify($data));
    }

    /**
     * 押金支付成功
     * @param Request $request
     * @param CarOrderTakeServices $services
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function alipayPay(Request $request,CarOrderTakeServices $services){
        $data = $request->postMore([
            ['take_id',''],
            ['trade_no',''],
            ['deposit_pay_type','alipay'],
            ['alipay_user_id','']
        ]);
        if(!$data['take_id']) return app('json')->fail('参数错误');
        return app('json')->success($services->alipayPay((int)$data['take_id'],$data));
    }

    /**
     * 预授权解冻
     * @param $take_id
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function alipayDepositThaw($take_id,$data){
        $take = CarOrderTake::find($take_id);
        $take = $take ? $take->toArray() : [];
        if(!$take) return app('json')->fail('未查询到数据');
        $alipayClient = $this->setConfig();
        $alipayClient->apiVersion = "1.0";
        $object = new \stdClass();
        $object->auth_no = $take['deposit_trade_no'];
        $object->out_request_no = self::getNewOrderId('CarUnfreeDepositOrder', 'u');
        $object->amount = $data['price'];
        $object->remark = '租车押金解冻';
        $object->extra_param = json_encode(['unfreezeBizInfo' => ['bizComplete' => true]]);
        $json = json_encode($object);
        $request = new \AlipayFundAuthOrderUnfreezeRequest();
        $request->setNotifyUrl($this->domain . '/AlipayFundAuthOrderUnfreezeNotify');
        $request->setBizContent($json);
        $result = $alipayClient->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode;
        $res = $this->object_to_array($resultCode);
        return $res;
    }

    /**
     * 获取素材内容
     * @return mixed
     */
    public function getSysConfig()
    {
        //服务提供
        $data['service_provide'] = sys_config('service_provide');
        //服务详情
        $data['service_detail'] = sys_config('service_detail');
        //守约奖励
        $data['observant_gift'] = sys_config('observant_gift');
        //芝麻信用免押介绍
        $data['free_deposit_detail'] = sys_config('free_deposit_detail');
        //资金授权介绍
        $data['ali_fee_authorization'] = sys_config('ali_fee_authoriztion');
        //免押协议
        $data['free_deposit_deal'] = sys_config('free_deposit_deal');
        //支付宝首页背景
        $data['ali_homepage_background'] = sys_config('ali_homepage_background');
        //个人背景图片
        $data['personal_page_background'] = sys_config('personal_page_background');
        //申请免押
        $data['apply_deposit_background'] = sys_config('apply_deposit_background');
        //查询免押背景
        $data['free_deposit_background'] = sys_config('free_deposit_background');
        //登录页头部图片
        $data['login_head_image'] = sys_config('login_head_image');
        //申请免押温馨提示
        $data['free_deposit_tip'] = sys_config('free_deposit_tip');
        return app('json')->successful($data);
    }

    /**
     * 创建订单
     * @param Request $request
     * @param CarOrderTakeServices $services
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function Alipay(Request $request){
        $data = $request->postMore([
            ['pay_type','wxpay'],//1是正式2是测试3是AI约你游
            ['appid','2'],//1是正式2是测试3是AI约你游
            ['vendorid',''],//商户id
            ['order_type',''],//订单类型 1直营商户 2入驻商户
            ['out_trade_no',''],//订单号
            ['total_amount',''],//订单总金额
            ['subject',''],//订单标题
            ['quantity',''],//商品数量
            ['price',''],//订单商品单价
        ]);
        if(!$data) return app('json')->fail('参数错误');
        $ret = $this->services->Alipay($data);
        return app('json')->success($ret);
    }
}

